package com.imooc.bilibili.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * ProjectName imooc-bilibili
 *
 * @author xieyucan
 * <br>CreateDate 2022/10/26 13:47
 */
@Slf4j
@EnableAsync
@Configuration
public class AsyncThreadPoolConfig implements AsyncConfigurer {

    @Bean(value = "getAsyncExecutor")
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //设置核心线程数量
        executor.setCorePoolSize(3);
        //设置最大线程数量
        executor.setMaxPoolSize(5);
        //设置线程前缀名称
        executor.setThreadNamePrefix("xieYuCan-");
        //设置阻塞队列容量
        executor.setQueueCapacity(20);
        //保存线程存活时间
        executor.setKeepAliveSeconds(60);
        //设置关闭时，是否等待任务执行完成
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //设置终端等待最大时间
        executor.setAwaitTerminationSeconds(60);
        //设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //初始化线程池
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncExceptionHandler();
    }

    class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler
    {
        @Override
        public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
            log.error("Async error:[{}],method:[{}],param:[{}]",
                    throwable.getMessage(),method.getName(), JSON.toJSONString(objects));

            //TODO 发送邮件或者短信，做进一步的报警处理
        }
    }
}
